package com.itheima.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器 处理自义定业务逻辑
 *      处理身份认证鉴权
 *	http://localhost:7001/user/cf?authorization=admin
 */
@Component
//@Order(-1) //值越小优先级越高 不会生效（当前网关源码存在问题）
public class AuthorizeFilter implements GlobalFilter, Ordered {

    /**
     * 身份认证鉴权
     *  判断请求路径中是否包含参数 authorization=admin 则放行
     *    如果不是则401权限不足
     * @param exchange the current server exchange 通过此对象获取请求和响应对象
     * @param chain provides a way to delegate to the next filter 过滤器对象-放行
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象 响应对象
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //2.获取请求参数authorization 【如果是真实项目，应获取请求头request.getHeaders() 然后在用jwt解析】
        String authorization = request.getQueryParams().getFirst("authorization");
        //3.判断参数值是否是admin
        if(authorization.equals("admin")) {
            //4.如果是则放行 chain
            return chain.filter(exchange);
        }
        //5.如果不是admin 则设置没有权限的状态码 401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //6.执行结束
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
